﻿using System.Security.Cryptography;

namespace AbpTool.Utils
{
    public static class SftpHelper
    {
        public static bool UploadFile(this SftpConnectionPool sftpConnectionPool, string localPath, string remotePath)
        {
            var client = sftpConnectionPool.GetConnection();
            try
            {
                // 确保远程目录存在
                var remoteDir = Path.GetDirectoryName(remotePath).Replace('\\', '/');
                sftpConnectionPool.CreateRemoteDirectory(remoteDir);

                using (var fileStream = new FileStream(localPath, FileMode.Open))
                {
                    client.UploadFile(fileStream, remotePath);
                }

                return true;

            }
            catch (Exception ex)
            {
                Console.WriteLine($"文件上传失败: {ex.Message}");
                return false;
            }
            finally
            {
                sftpConnectionPool.ReturnConnection(client);
            }
        }

        private static void CreateRemoteDirectory(this SftpConnectionPool sftpConnectionPool, string remotePath)
        {
            var directories = remotePath.Split('/', StringSplitOptions.RemoveEmptyEntries);
            var currentPath = "";
            var client = sftpConnectionPool.GetConnection();
            try
            {
                foreach (var dir in directories)
                {
                    currentPath += $"/{dir}";
                    try
                    {
                        client.CreateDirectory(currentPath);
                    }
                    catch
                    {
                        // 目录可能已存在
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                sftpConnectionPool.ReturnConnection(client);
            }

        }

        public static string CalculateFileChecksum(this SftpConnectionPool sftpConnectionPool, string filePath)
        {
            using (var md5 = MD5.Create())
            using (var stream = File.OpenRead(filePath))
            {
                var hash = md5.ComputeHash(stream);
                return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
            }
        }

        public static bool VerifyRemoteFile(this SftpConnectionPool sftpConnectionPool, string localPath, string remotePath)
        {
            var client = sftpConnectionPool.GetConnection();
            try
            {
                var localChecksum = sftpConnectionPool.CalculateFileChecksum(localPath);

                // 下载远程文件到临时位置进行校验
                var tempPath = Path.GetTempFileName();
                using (var fileStream = new FileStream(tempPath, FileMode.Create))
                {
                    client.DownloadFile(remotePath, fileStream);
                }

                var remoteChecksum = sftpConnectionPool.CalculateFileChecksum(tempPath);
                File.Delete(tempPath);


                return localChecksum == remoteChecksum;

            }
            catch
            {
                return false;
            }
            finally
            {
                sftpConnectionPool.ReturnConnection(client);
            }
        }
    }
}
